package com.taropan.wallpaper.util;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Vector;

import android.os.Environment;
import android.os.StatFs;

public class FileOperation {

	private String filename = null;
	private String rootName = null;
	private String suffix = ".dat";
	public static final String PATH = android.os.Environment.getExternalStorageDirectory().getPath()+ "/com.taropan.wallpaper/";
	public int startPosition;
	public boolean insertdata = false;
	private static String secondarydir = "";
	private File file;

	/**
	 * 二级目录名
	 * 
	 * @param dir
	 */
	public FileOperation(String dir, String suffix) {
		secondarydir = dir;
		if (suffix != null)
			this.suffix = suffix;
	}

	/**
	 * 创建打开文件
	 * 
	 * @param name
	 */
	public boolean initFile(String name) {
		filename = PATH + secondarydir + "/";
		if (FileOperation.checkSDcard()) {

			try {
				if (name != null && name.length() > 1) {
					file = new File(filename);
					if (!file.exists()) {
						file.mkdirs();
					}
					if (name != null && !"".equals(name)) {
						filename = filename + name + suffix;
						file = new File(filename);
						if (!file.exists()) {
							file.createNewFile();// 文件不存在则新建
						}
					}
				} else {
					file = new File(filename);
					if (!file.exists()) {
						file.mkdirs();
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				System.out.println("创建文件失败");
				return false;
			}
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 创建打开文件
	 * 
	 * @param name
	 */
	public boolean initFile(String path, String name) {
		filename = path + secondarydir + "/";
		if (FileOperation.checkSDcard()) {

			try {
				if (name != null && name.length() > 1) {
					file = new File(filename);
					if (!file.exists()) {
						file.mkdirs();
					}
					if (name != null && !"".equals(name)) {
						filename = filename + name + suffix;
						file = new File(filename);
						if (!file.exists()) {
							file.createNewFile();// 文件不存在则新建
						}
					}
				} else {
					file = new File(filename);
					if (!file.exists()) {
						file.mkdirs();
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				System.out.println("创建文件失败");
				return false;
			}
			return true;
		} else {
			return false;
		}
	}
	
	public long getFileSize()
	{
	    if (!file.exists()) {
            return -1;
        }
	    return file.length();
	}

	/**
	 * 检测是否支持存储卡
	 * 
	 * @return
	 */
	public static String getRootName() {
		try {
			if (Environment.getExternalStorageState().equals(
					Environment.MEDIA_MOUNTED)) {
				return "可用sdcrad";
			} else {
				return null;
			}
		} catch (Exception e) {
			return null;
		}
	}

	/*
	 * 判断是否有SD卡
	 */
	public synchronized static boolean checkSDcard() {
		String status = android.os.Environment.getExternalStorageState();
		if (status.equals(android.os.Environment.MEDIA_MOUNTED)) {
			return true;
		} else {
			return false;
		}
	}

	public synchronized static boolean lowSDcard() {
		if (getAvailaleSize() <= 5 * 1024 * 1024) {
			return true;
		}
		return false;
	}

	public static long getAvailaleSize() {
		File path = Environment.getExternalStorageDirectory();
		StatFs stat = new StatFs(path.getPath());
		/* 获取block的SIZE */
		long blockSize = stat.getBlockSize();
		/* 空闲的Block的数量 */
		long availableBlocks = stat.getAvailableBlocks();
		/* 返回bit大小值 */
		return availableBlocks * blockSize;
	}

	/**
	 * 获取文件列表
	 * 
	 * @param path
	 * @return
	 */
	public String[] getFileList() {
		if (FileOperation.checkSDcard()) {
			Vector<String> fileName = new Vector<String>();
			if (file.exists() && file.isDirectory()) {
				String[] str = file.list();
				for (String s : str) {
					if (new File(filename + s).isFile()) {

						fileName.addElement(s.substring(0, s.lastIndexOf(".")));
					}
				}
				return fileName.toArray(new String[] {});
			}
		}
		return null;
	}
	
	

	/**
	 * 添加一行记录
	 * 
	 * @param data
	 */
	public boolean addLine(byte[] data) {
		if (FileOperation.checkSDcard()) {
			if (!file.exists()) {
				return false;
			}
			try {

				FileOutputStream fos = new FileOutputStream(file);
				fos.write(data);
				fos.close();
			} catch (FileNotFoundException e) {
				System.out.println("写存储卡错误");
				e.printStackTrace();
				return false;
			} catch (IOException e) {
				System.out.println("写存储卡错误");
				e.printStackTrace();
				return false;
			}
		}
		return true;
	}

	public void closeFile() {
		try {
			if (file != null) {
				file = null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 返回当前文件流
	 * 
	 * @return
	 */
	public byte[] getData() {
		if (FileOperation.checkSDcard()) {
			if (file == null || !file.exists()) {
				return null;
			}
			int length = (int) file.length();
			byte[] b = new byte[length];
			try {
				FileInputStream fis = new FileInputStream(file);
				fis.read(b, 0, length);
				fis.close();
			} catch (FileNotFoundException e) {

			} catch (IOException e) {
			}
			return length != 0 ? b : null;
		}
		return null;
	}

	public boolean extraAddLine(byte[] data) {
		if (FileOperation.checkSDcard()) {
			if (file == null || !file.exists()) {
				return false;
			}
			int length = (int) file.length();
			byte[] b = new byte[length];
			try {
				FileInputStream fis = new FileInputStream(file);
				fis.read(b, 0, length);
				fis.close();
			} catch (FileNotFoundException e) {

			} catch (IOException e) {
			}
			try {
				FileOutputStream fos = new FileOutputStream(file);
				if (b != null)
					fos.write(b);
				fos.write(data);
				fos.close();
			} catch (FileNotFoundException e) {
				System.out.println("写存储卡错误");
				e.printStackTrace();
				return false;
			} catch (IOException e) {
				System.out.println("写存储卡错误");
				e.printStackTrace();
				return false;
			}
		}
		return true;
	}

	/**
	 * 删除文件
	 */
	public boolean deleteFile() {

		try {
			if (file != null)
				file.delete();
		} catch (Exception e) {
			System.out.println("删除文件IO异常");

			return false;
		}
		return true;
	}

	/**
	 * 判断文件是否存在
	 * 
	 * @param name
	 * @return
	 */
	public boolean exist(String name) {
		String mypath = PATH + secondarydir + "/";
		File file = new File(mypath, name + suffix);
		return file.exists();
	}

	/**
	 * 删除目录 如果目录下有子目录或文件，也全部删除
	 * 
	 * @param pathName
	 */
	public static boolean deletDirectory(String pathName) {
		boolean del = false;
		if (FileOperation.checkSDcard()) {
			File file = new File(pathName);
			if (file.exists()) {
				if (file.isFile()) {
					file.delete();
				} else if (file.isDirectory()) {

					String[] f = file.list();
					for (int i = 0; i < f.length; i++) {
						deletDirectory(pathName + "/" + f[i]);
					}
					del = file.delete();
				}
			}
		}
		return del;
	}

	public static void deleteAllFile() {
		delDir(PATH);
	}

	/**
	 * 删除目录 如果目录下有子目录或文件，也全部删除
	 */
	private static void delDir(String pathName) {

		boolean del = false;
		File file = new File(pathName);
		if (file.exists()) {
			if (file.isFile()) {
				file.delete();
			} else if (file.isDirectory()) {
				String[] f = file.list();
				for (int i = 0; i < f.length; i++) {
					deletDirectory(pathName + "/" + f[i]);
				}
				del = file.delete();
			}
		}
	}

	/*--------------用于下载----------------------*/
	/**
	 * 获得下载file
	 * 
	 * @param fileName
	 * @param downloadSize
	 *            已下载的长度
	 * @return
	 */
	public File initDownloadFile(String fileName) {
		if (null == fileName)
			file = null;
		filename = PATH + secondarydir;
		file = new File(filename);
		if (!file.exists())
			file.mkdirs();
		file = new File(filename, fileName + suffix);
		return file;
	}

	public File getDownloadFile(String fileName) {
		return new File(PATH + secondarydir + '/' + fileName);
	}

	public static String getDownloadedFilePath(String fileName) {
		return PATH + secondarydir + '/' + fileName;
	}

	/**
	 * 获得下载 文件夹里的文件
	 * 
	 * @return
	 */
	public File[] getDowloadFiles() {
		filename = PATH + secondarydir;
		file = new File(filename);
		if (!file.exists())
			return null;
		else
			return file.listFiles();
	}
	/**
	 * 遍历翼讯全文件
	 * @param name
	 */
	/**
	* 删除目录
	* 如果目录下有子目录或文件，也全部删除
	*/
	public boolean initAllFile(String name){
		String fname = name+suffix;
		File dir = new File(PATH);
		if(dir.exists() && dir.isDirectory()){
			File[] f = dir.listFiles();
			for(int i=0;i<f.length;i++){
				if(initAllFile(f[i],fname)){
					return true;
				}
			}
		}
		return false;
	 }
	private boolean initAllFile(File dir,String name){
		if(FileOperation.checkSDcard() && name!=null && !"".equals(name.trim())){		
			//System.out.println(dir.getPath());
			if(dir.exists()){
				if(dir.isDirectory()){
					File[] f = dir.listFiles();
					for(int i=0;i<f.length;i++){
						if(initAllFile(f[i],name)){
							return true;
						}
					}
				}else if(dir.isFile() && dir.exists() && dir.length()>0 && name.equals(dir.getName())){
					file = dir;
					filename = dir.getPath();
					return true;
				}
			}			
		}
		return false;
		
	}

	/*------------------------------------*/
	public static File getFileFromBytes(byte[] b, String outputFile) {
		BufferedOutputStream stream = null;
		File file = null;
		try {
			file = new File("/ssdadad");
			FileOutputStream fstream = new FileOutputStream(file);
			stream = new BufferedOutputStream(fstream);
			stream.write(b);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (stream != null) {
				try {
					stream.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
		return file;
	}

	public File getFile() {
		return file;
	}
	
}
